(() => {
  "use strict";
  function e(e, t) {
    (null == t || t > e.length) && (t = e.length);
    for (var n = 0, o = new Array(t); n < t; n++) o[n] = e[n];
    return o;
  }
  function t(t) {
    return (
      (function (t) {
        if (Array.isArray(t)) return e(t);
      })(t) ||
      (function (e) {
        if ("undefined" != typeof Symbol && Symbol.iterator in Object(e))
          return Array.from(e);
      })(t) ||
      (function (t, n) {
        if (t) {
          if ("string" == typeof t) return e(t, n);
          var o = Object.prototype.toString.call(t).slice(8, -1);
          return (
            "Object" === o && t.constructor && (o = t.constructor.name),
            "Map" === o || "Set" === o
              ? Array.from(t)
              : "Arguments" === o ||
                  /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(o)
                ? e(t, n)
                : void 0
          );
        }
      })(t) ||
      (function () {
        throw new TypeError(
          "Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.",
        );
      })()
    );
  }
  function n(e, t) {
    var n;
    if ("undefined" == typeof Symbol || null == e[Symbol.iterator]) {
      if (
        Array.isArray(e) ||
        (n = (function (e, t) {
          if (!e) return;
          if ("string" == typeof e) return o(e, t);
          var n = Object.prototype.toString.call(e).slice(8, -1);
          "Object" === n && e.constructor && (n = e.constructor.name);
          if ("Map" === n || "Set" === n) return Array.from(e);
          if (
            "Arguments" === n ||
            /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)
          )
            return o(e, t);
        })(e)) ||
        (t && e && "number" == typeof e.length)
      ) {
        n && (e = n);
        var i = 0,
          a = function () {};
        return {
          s: a,
          n: function () {
            return i >= e.length ? { done: !0 } : { done: !1, value: e[i++] };
          },
          e: function (e) {
            throw e;
          },
          f: a,
        };
      }
      throw new TypeError(
        "Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.",
      );
    }
    var s,
      c = !0,
      r = !1;
    return {
      s: function () {
        n = e[Symbol.iterator]();
      },
      n: function () {
        var e = n.next();
        return (c = e.done), e;
      },
      e: function (e) {
        (r = !0), (s = e);
      },
      f: function () {
        try {
          c || null == n.return || n.return();
        } finally {
          if (r) throw s;
        }
      },
    };
  }
  function o(e, t) {
    (null == t || t > e.length) && (t = e.length);
    for (var n = 0, o = new Array(t); n < t; n++) o[n] = e[n];
    return o;
  }
  function i(e, t, n) {
    chrome.extension.sendMessage(
      { action: "setCache", name: e, value: t },
      function (e) {
        n && n(e);
      },
    );
  }
  var a = null;
  function s() {
    var e = {};
    return (
      (e.title = document.body.getAttribute("data-msg_title")),
      (e.content = $("#js_content").html()),
      (e.thumb = document.body.getAttribute("data-msg_cdn_url")),
      (e.desc = document.body.getAttribute("data-msg_desc")),
      (e.nickname = document.body.getAttribute("data-nickname")),
      (e.publish_time = document.body.getAttribute("data-ct")),
      (e.link = window.location.href),
      console.log(e),
      e
    );
  }
  function c(e, t) {
    void 0 === t && (t = window.location.href);
    var n = t.match("[?&]" + e + "=([^&]+)");
    return n ? n[1] : null;
  }
  
  if (
    (setTimeout(function () {
      var e = document.createElement("script");
      (e.type = "text/javascript"),
        (e.innerHTML =
          "if(typeof msg_desc != 'undefined') { document.body.setAttribute('data-ct', ct); document.body.setAttribute('data-nickname', nickname); document.body.setAttribute('data-msg_desc', msg_desc );document.body.setAttribute('data-msg_title', msg_title);document.body.setAttribute('data-msg_cdn_url', msg_cdn_url); }"),
        document.head.appendChild(e),
        document.head.removeChild(e);
    }, 50),
    console.log("accounts", k),
    window.location.href.indexOf("mp.weixin.qq.com/s") > -1)
  ) {
    var r = $(
      "<div style='display: inline-block;'></div>",
    );
    r.append(
      '<div data-toggle="modal" data-target="#exampleModalCenter" style="font-size: 14px; cursor: pointer; color: #007bff; text-decoration: underline;">同步该文章</div>',
    ),
      r.click(function () {
      _(function () {
        !(function () {
        var e = s(),
          t = "";
        (k = w),
          w
          .filter(function (e) {
            return !e.supportTypes || e.supportTypes.indexOf("html") > -1;
          })
          .forEach(function (e, n) {
            t +=
            '\n            <div class="form-check mb-1">\n  <input class="form-check-input" type="checkbox" value="' +
            e.uid +
            '" name="submit_check" id="defaultCheck' +
            n +
            '">\n  <label class="form-check-label" for="defaultCheck' +
            n +
            '">\n  <img src="' +
            (e.icon
              ? e.icon
              : chrome.extension.getURL("images/wordpress.ico")) +
            '" class="icon" height="20" style="vertical-align: -3px;height: 20px !important">\n  ' +
            e.title +
            "\n  </label>\n</div>\n            ";
          });
          var n =
          '\n        <div class="media">\n        <img class="align-self-center mr-3" src="' +
          e.thumb +
          '" width="150" alt="Generic placeholder image">\n        <div class="media-body">\n          <h5 class="mt-0" style="font-weight:bold">' +
          e.title +
          "</h5>\n          <p>" +
          e.desc +
          '</p>\n        </div>\n      </div>\n      <hr>\n      <div id="top-tip-block"></div>\n      <h6>可同步账号</h6>\n      <div id="syncd-users" class="mb-3">\n      ' +
          t +
          '\n      </div>';
        
        // 已登录列表
        const loggedInDomains = w.map(account => {
          const url = account.icon;
          const domain = url.match(/https?:\/\/([^\/]+)/)[1];
          return domain;
        });

        // 平台
        const allPlatforms = [
          {name: '百家号', domain: 'baidu.com', icon: 'https://www.baidu.com/favicon.ico?t=20171027'},
          {name: '知乎', domain: 'zhihu.com', icon: 'https://static.zhihu.com/static/favicon.ico'},
          {name: '微博', domain: 'weibo.com', icon: 'https://weibo.com/favicon.ico'},
          {name: 'B站', domain: 'bilibili.com', icon: 'https://www.bilibili.com/favicon.ico'}
        ];

        const notLoggedInPlatforms = allPlatforms.filter(
          platform => !loggedInDomains.some(domain => domain.includes(platform.domain))
        );
        
        let notLoggedInHTML = '';
        if(notLoggedInPlatforms.length > 0) {
          notLoggedInHTML = `
            <h6 class="mt-4">未登录平台</h6>
            <div class="not-logged-in">
              ${notLoggedInPlatforms.map(platform => `
                <div class="d-flex align-items-center text-muted mb-2">
                  <img src="${platform.icon}" class="icon mr-2" height="20" style="vertical-align: -3px;height: 20px !important">
                  <span>${platform.name}</span>
                </div>
              `).join('')}
            </div>
          `;
        }
        
        // 添加未登录平台和tip-block
        n += notLoggedInHTML + '\n      <div id="tip-block"></div>\n        ';

        $("#exampleModalCenter .modal-body").html(""),
          $("#exampleModalCenter .modal-body").append(n),
          console.log("clicka"),
          M(),
          $("#syncd-users").click(y);
        })();
      });
      }),
      $("#meta_content").append(r);
  }
  $("body").append(
    '\n<!-- Modal -->\n<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">\n  <div class="modal-dialog modal-dialog-centered" role="document" style="color: #444;">\n    <div class="modal-content">\n      <div class="modal-header">\n        <h5 class="modal-title" id="exampleModalLongTitle">同步文章</h5>\n        <button type="button" class="close" data-dismiss="modal" aria-label="Close" id="closesyncmodl">\n          <span aria-hidden="true">&times;</span>\n        </button>\n      </div>\n      <div class="modal-body">\n\n      </div>\n      <div class="modal-footer">\n        <button type="button" class="btn btn-secondary" data-dismiss="modal" style="font-size: 13px;    line-height: 1.5;">取消</button>\n        <button type="button" class="btn btn-primary" style="font-size: 13px;    line-height: 1.5;">同步</button>\n      </div>\n    </div>\n  </div>\n</div>\n',
  ),
    $("body").append(
      // '\n<div data-toggle="modal" data-target="#exampleModalCenterForShare" id="sharetrigger"></div>\n<!-- Modal -->\n<div class="modal fade" id="exampleModalCenterForShare" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterForShareTitle" aria-hidden="true">\n  <div class="modal-dialog modal-sm modal-dialog-centered modal-dialog-scrollable" role="document" style="color: #444;">\n    <div class="modal-content">\n      <div class="modal-header">\n        <h5 class="modal-title" id="exampleModalLongTitle">求分享</h5>\n        <button type="button" class="close" data-dismiss="modal" aria-label="Close" id="closesyncmodl">\n          <span aria-hidden="true">&times;</span>\n        </button>\n      </div>\n      <div class="modal-body">\n <div><h3 style="color: #aaa;font-size: 16px;">请帮忙分享给有需要的人！</h3>\n <p id="doubanshare" style="/* margin-top: 17px */">\n </p>\n <p id="weiboshare" style="margin-bottom: 25px;">\n</p>\n<h3 style="color: #666;font-size: 16px;">或复制分享</h3><textarea style="\n    width: 100%;\n    height: 200px;\n    background: #eee;\n    color: #777;\n    padding: 10px;\n    border: 1px solid #ddd;\n    "\n    id="sshare-text"\n    ></textarea></div>\n    </div>\n    </div>\n  </div>\n</div>\n',
    );
  var l = !1,
    d = 0,
    u = "total_sync",
    m = "detect_share",
    h = "share_showed",
    p = 0,
    g = null,
    f = !1;
  function b(e) {
    (f = !0),
      (function (e, t, n) {
        chrome.extension.sendMessage(
          { action: "sendEvent", event: { category: e, action: t, label: n } },
          function (e) {
            cb && cb(e);
          },
        );
      })(
        "share",
        e,
        [
          a
            ? a.accounts.map(function (e) {
                return [e.type, e.uid, e.title].join("-");
              })
            : "default",
          d,
        ].join(";;"),
      );
  }
  function v() {
    if (d < 5 ? d > 1 && d % 2 == 0 : d % 3 == 0) {
      if (l) return;
      $("#sharetrigger").click(), (g = Date.now()), i(h, p + 1);
    }
  }
  function y() {
    if ((console.log("checkShareStatus"), g)) {
      var e = Date.now() - g;
      e > 12e3 && f && (console.log("reach share action"), i(m, "1")),
        console.log("spendTime", e);
    }
  }
  setTimeout(function () {
    var e = document.getElementById("sshare-text"),
      t = document.getElementById("doubanshare"),
      n = document.getElementById("weiboshare"),
      o = "https://www.wechatsync.com/?utm_source=byshare",
      i =
        "文章同步助手 - 一键同步文章到头条、百家号等多达20个渠道，提高内容发布效率，解放生产力！";
    (e.innerHTML = i + " " + o),
      (e.onselect = function () {
        b("share-selected");
      }),
      t.addEventListener("click", function () {
        var e, t, n, a, s, c, r, l;
        b("douban-clicked"),
          (e = document),
          (t = encodeURIComponent),
          (n = window.getSelection),
          (a = e.getSelection),
          (s = e.selection),
          (c = n ? n() : a ? a() : s ? s.createRange().text : ""),
          (r =
            "https://www.douban.com/recommend/?url=" +
            t(o) +
            "&title=" +
            t(i) +
            "&sel=" +
            t(c) +
            "&v=1"),
          (l = function () {
            window.open(
              r,
              "douban",
              "toolbar=0,resizable=1,scrollbars=yes,status=1,width=450,height=330,left=" +
                (screen.width - 450) / 2 +
                ",top=" +
                (screen.height - 330) / 2,
            ) || (location.href = r + "&r=1");
          }),
          /Firefox/.test(navigator.userAgent) ? setTimeout(l, 0) : l();
      }),
      n.addEventListener("click", function () {
        var e, t, n, a, s, c, r;
        b("weibo-clicked"),
          (e = document),
          (t = encodeURIComponent),
          (n = window.getSelection),
          (a = e.getSelection),
          (s = e.selection),
          n ? n() : a ? a() : s && s.createRange().text,
          (c =
            "https://service.weibo.com/share/share.php?url=" +
            t(o) +
            "&language=zh_cn&title=" +
            t(i) +
            "%20%40_fun0&source=&sourceUrl=&ralateUid=&message=&uids=&pic=&searchPic=false&content="),
          (r = function () {
            window.open(
              c,
              "weibo",
              "toolbar=0,resizable=1,scrollbars=yes,status=1,width=450,height=330,left=" +
                (screen.width - 450) / 2 +
                ",top=" +
                (screen.height - 330) / 2,
            ) || (location.href = c + "&r=1");
          }),
          /Firefox/.test(navigator.userAgent) ? setTimeout(r, 0) : r();
      }),
      (t.innerHTML =
        '<a ><img src="https://img3.doubanio.com/pics/fw2douban1.png" alt="推荐到豆瓣" /></a>'),
      (n.innerHTML =
        '<a style="font-size: 13px"><img height="18" src="https://cambrian-images.cdn.bcebos.com/a487b054820191e8e7a2fcf136b925b9_1551320091220.jpeg" style="vertical-align: -3px;" /> 分享到微博</a>');
  }, 200),
    chrome.runtime.onMessage.addListener(function (e, t, n) {
      console.log("content.js revice", e);
      try {
        console.log("revice", e),
          "taskUpdate" == e.method &&
            (function (e) {
              var t = $(".alld-pubaccounts").length;
              a = e;
              var n =
                  e.accounts.filter(function (e) {
                    return "done" == e.status;
                  }).length == e.accounts.length,
                o = e.accounts.map(function (e) {
                  var n =
                    ("uploading" == e.status
                      ? ' <div class="lds-dual-ring"></div>' +
                        (e.msg ? e.msg : "同步中")
                      : "") +
                    ("failed" == e.status
                      ? "同步失败, 错误内容：" + e.error
                      : "") +
                    ("done" == e.status && e.editResp
                      ? '同步成功 <a\n                      href="' +
                        e.editResp.draftLink +
                        '"\n                      style="margin-left: 5px"\n                      target="_blank"\n                      >查看草稿</a\n                    >'
                      : "");
                  if (t) {
                    var o = $("." + e.type + "-message");
                    return o.length && o.html(n), n;
                  }
                  return (
                    '<div class="account-item taskStatus">\n                 ' +
                    (e.icon
                      ? ' <img src="' +
                        e.icon +
                        '" class="icon"\n      width="20"\n      height="20"\n      style="vertical-align: -6px;height: 20px !important"\n    />'
                      : "") +
                    '<span class="name-block">' +
                    e.title +
                    '</span><span\n                  style="margin-left: 15px"\n                  class="' +
                    e.type +
                    "-message " +
                    e.status +
                    ' message"\n                >\n                  ' +
                    n +
                    "</span></div>"
                  );
                }),
                s =
                  '\n  <div class="alld-pubaccounts">\n  ' +
                  o.join("\n") +
                  "</div>";
              console.log(o, s), t || $("#syncd-users").html(s);
              n && (console.log("all done, notify share"), i(u, d + 1), v());
            })(e.task);
      } catch (e) {
        console.log(e);
      }
    }),
    (function (e, t) {
      chrome.extension.sendMessage(
        { action: "getCache", names: e },
        function (e) {
          t && t(e.result);
        },
      );
    })([m, u, h], function (e) {
      console.log("result", e),
        e[m] && (l = !0),
        e.total_sync && (d = parseInt(e.total_sync)),
        e.share_showed && (p = parseInt(e.share_showed));
    }),
    $("#exampleModalCenter .btn-primary").click(function (e) {
      var t = A();
      if (!t.length) return alert("请选择账号"), e.stopPropagation();
      chrome.extension.sendMessage(
        { action: "addTask", task: { post: s(), accounts: t } },
        function (e) {
          console.log("addTask return", e);
        },
      ),
        $("#syncd-users").html("等待发布...");
    });
  var x,
    w = [],
    k = [];
  function _(e) {
    chrome.extension.sendMessage({ action: "getAccount" }, function (t) {
      (w = t), e && e();
    });
  }
  function M() {
    for (
      var e = $('input[name="submit_check"]'),
        t = localStorage.getItem("_sync_checked_all")
          ? JSON.parse(localStorage.getItem("_sync_checked_all"))
          : [],
        n = function (n) {
          var o = e[n];
          t.filter(function (e) {
            return e.uid == o.value;
          }).length && (o.checked = !0);
        },
        o = 0;
      o < e.length;
      o++
    ) {
      n(o);
    }
  }
  function A() {
    for (
      var e = $('input[name="submit_check"]'),
        t = [],
        n = function (n) {
          var o = e[n];
          o.checked &&
            ((i = k.filter(function (e) {
              return e.uid == o.value;
            })),
            console.log(k, o.value),
            t.push(i[0]));
        },
        o = 0;
      o < e.length;
      o++
    ) {
      var i;
      n(o);
    }
    return (
      (function (e) {
        try {
          localStorage.setItem("_sync_checked_all", JSON.stringify(e));
        } catch (e) {}
      })(t),
      t
    );
  }
  if (window.location.href.indexOf("mp.weixin.qq.com/cgi-bin/appmsg") > -1) {
    var S = function () {
        _(function () {
          !(function () {
            var e =
              '\n        <h6 style="margin-bottom: 12px">同步助手</h6> <div id="syncform-selectbox" style="padding-left: 5px">';
            (k = w),
              w
                .filter(function (e) {
                  return !e.supportTypes || e.supportTypes.indexOf("html") > -1;
                })
                .forEach(function (t, n) {
                  e +=
                    '\n            <div class="form-check mb-1">\n  <input class="form-check-input" type="checkbox" value="' +
                    t.uid +
                    '" name="submit_check" id="defaultCheck' +
                    n +
                    '">\n  <label class="form-check-label" for="defaultCheck' +
                    n +
                    '">\n  <img src="' +
                    (t.icon
                      ? t.icon
                      : chrome.extension.getURL("images/wordpress.ico")) +
                    '" class="icon" height="18" style="height: 20px !important">\n  ' +
                    t.title +
                    "\n  </label>\n</div>\n            ";
                }),
              $(".mass-send__form").append(e + "</div>"),
              M(),
              console.log("html", e);
          })(),
            setTimeout(function () {
              $(".mass-send__footer .weui-desktop-btn_primary").click(
                function () {
                  console.log("clicked"),
                    A(),
                    (function e() {
                      var t = $(".weui-desktop-dialog__wrp").filter(
                        function () {
                          return (
                            $(this).text().indexOf("开始群发后无法撤销") > -1
                          );
                        },
                      );
                      t.length
                        ? t
                            .find(".weui-desktop-btn_primary")
                            .click(function () {
                              var e;
                              console.log("btn clicked"),
                                (e = A()),
                                console.log(
                                  "prepairSubmitTask",
                                  "syncform-selectbox",
                                  e,
                                ),
                                e.length
                                  ? chrome.extension.sendMessage(
                                      {
                                        action: "parseArticle",
                                        account: { type: "weixin" },
                                        data: { msgId: c("appmsgid") },
                                      },
                                      function (t) {
                                        T.show(),
                                          $("#syncd-users").html("等待发布..."),
                                          chrome.extension.sendMessage(
                                            {
                                              action: "addTask",
                                              task: {
                                                post: t.article,
                                                accounts: e,
                                              },
                                            },
                                            function (e) {
                                              console.log("addTask return", e);
                                            },
                                          ),
                                          console.log("parseArticle return", t);
                                      },
                                    )
                                  : console.log("selected", 0);
                            })
                        : setTimeout(e, 300);
                    })();
                },
              );
            }, 100);
        }),
          console.log("initSyncForm", w);
      },
      C = document.createElement("script");
    (C.type = "text/javascript"),
      (C.src = chrome.extension.getURL("autoformat.js")),
      C.setAttribute("data-url", chrome.runtime.getURL("templates.html")),
      document.head.appendChild(C);
    var T =
      ((x = $(
        '<div class="weui-desktop-dialog" style="position: fixed;\n    right: -25px;\n    top: 25px;\n    min-width: 350px;\n    width: 350px;\n    z-index: 99998;">\n    <div class="weui-desktop-dialog__hd" style="\n    line-height: 50px;\n    height: 50px;\n">\n  <h3 class="weui-desktop-dialog__title">同步助手</h3>\n    <button class="weui-desktop-icon-btn weui-desktop-dialog__close-btn"><svg width="18" height="18" viewBox="0 0 18 18" xmlns="http://www.w3.org/2000/svg"><path d="M10.01 8.996l7.922-7.922c.086-.086.085-.21.008-.289l-.73-.73c-.075-.074-.208-.075-.29.007L9 7.984 1.077.062C.995-.02.863-.019.788.055l-.73.73c-.078.078-.079.203.007.29l7.922 7.92-7.922 7.922c-.086.086-.085.212-.007.29l.73.73c.075.074.207.074.29-.008l7.92-7.921 7.922 7.921c.082.082.215.082.29.008l.73-.73c.077-.078.078-.204-.008-.29l-7.921-7.921z"></path></svg></button></div>\n    <div style="    width: 100%;\n    min-height: 300px;\n    background: white;">\n      <div id="syncd-users" style="padding: 0 32px"></div>\n      <div id="tip-block" style="padding: 0 32px"></div>\n    </div>\n  </div>',
      )),
      $("body").append(x),
      $("#exampleModalCenterForShare").css({ zIndex: "99998" }),
      x.hide(),
      x.find(".weui-desktop-dialog__close-btn").click(function () {
        x.hide();
      }),
      x);
    new MutationObserver(function (e) {
      var o,
        i = [],
        a = n(e);
      try {
        for (a.s(); !(o = a.n()).done; ) {
          var s,
            c = n(o.value.addedNodes);
          try {
            for (c.s(); !(s = c.n()).done; ) {
              var r = s.value;
              r.tagName &&
                (r.classList.contains("mass-send__list")
                  ? i.push(r)
                  : r.firstElementChild &&
                    i.push.apply(
                      i,
                      t(r.getElementsByClassName("mass-send__list")),
                    ));
            }
          } catch (e) {
            c.e(e);
          } finally {
            c.f();
          }
        }
      } catch (e) {
        a.e(e);
      } finally {
        a.f();
      }
      i.length && (console.log("onMutation.found", i), S());
    }).observe(document, { childList: !0, subtree: !0 });
  }
})();
